<?php
namespace Common\Model;
use Common\Model\BaseModel;
/**
 * ModelName
 */
class GoodsModel extends BaseModel{
    // 自动验证
    protected $_validate=array(
        array('title','require','文章标题必须',0,'',1), // 验证字段必填
    );

    // 自动完成
    protected $_auto=array(
        array('create_time','time',1,'function'), // 对date字段在新增的时候写入当前时间戳
    );

    //获取后台文章分页列表
    public function getAdminList($param){
        $keyword = $param['keyword'];
        $categoryId = $param['cateid'];
        if (!empty($keyword)) {
            $map['title'] = array('like','%'.$keyword.'%');
        }
        if (!empty($categoryId)) {
            $pid = M('GoodsCategory')->where('id='.$categoryId)->getField('pid');
            if($pid == 0){
                $cateList = M('GoodsCategory')->where('pid='.$categoryId)->select();
                if(count($cateList) != 0){
                    foreach ($cateList as $key => $value) {
                        $arr[] = $value['id'];
                    }
                    $map['cid'] = array('in', $arr);
                }else{
                    $map['cid'] = array('eq',$categoryId);
                }
            }else{
                $map['cid'] = array('eq',$categoryId);
            }
        }
        $assign = $this->getAdminPage($this,$map,$param,'id desc');
        return $assign;
    }

    /**
     * 添加文章
     */
    public function addData($data,$substr=false){
        // 对data数据进行验证
        if(!$data=$this->create($data)){
            // 验证不通过返回错误
            return false;
        }else{
            // 验证通过
            $data['content']=htmlspecialchars_decode($data['content']);
            if($substr == true && $data['info'] == null){
                $data['info'] = re_substr(strip_tags($data['content']),0,199);
            }
            $data['content']=preg_replace('/src=\"^\/.*\/Upload\/image\/ueditor$/','src="/Upload/image/ueditor',$data['content']);
            $data['content']=htmlspecialchars($data['content']);
            $data['author'] = $_SESSION['user']['id'];
            if($data['release_time'] == null){
                $data['release_time'] = time();
            }else{
                $data['release_time'] = strtotime($data['release_time']);
            }
            $result=$this->add($data);
            $this->addExpand(I('post.'), $result);
            return $result;
        }
    }

    /**
     * 修改文章
     */
    public function editData($map,$data,$substr=false){
        // 对data数据进行验证
        if(!$data=$this->create($data)){
            // 验证不通过返回错误
            return false;
        }else{
            $data['content']=htmlspecialchars_decode($data['content']);
            if($substr == true && $data['info'] == null){
                $data['info'] = re_substr(strip_tags($data['content']),0,199);
            }
            $data['content']=preg_replace('/src=\"^\/.*\/Upload\/image\/ueditor$/','src="/Upload/image/ueditor',$data['content']);
            $data['content']=htmlspecialchars($data['content']);
            // 验证通过
            $result=$this
                ->where(array($map))
                ->save($data);
            //$this->addExpand(I('post.'), $data['id']);
            return $result;
        }
    }

    /**
     * 获取文章详情
     */
    public function getData($map){
        $data = $this->where($map)->find();
        $data['content']=htmlspecialchars_decode($data['content']);
        $data['content']=preg_replace('/src=\"^\/.*\/Upload\/image\/ueditor$/','src="/Upload/image/ueditor',$data['content']);
        $data['album'] = M('GoodsAlbum')->where('aid='.$data['id'])->select();
        return $data;
    }

     /**
     * 删除数据
     * @param   array   $map    where语句数组形式
     * @return  boolean         操作是否成功
     */
    public function deleteData($map){
        $list = $this->where($map)->select();
        $result = $this->where($map)->delete();
        if($result){
            foreach ($list as $key => $value) {
                //删除logo
                deleteFile($value['pic_path']);  
                //删除相册
                $albumList = M('GoodsAlbum')->where('aid='.$value['id'])->select();
                M('GoodsAlbum')->where('aid='.$value['id'])->delete();
                foreach ($albumList as $k => $v) {
                    deleteFile($v['path']);
                }
                //删除拓展字段
                //M('GoodsExpand')->where('aid='.$value['id'])->delete();
            }
            return true;
        }else{
            return false;
        }
    }

    //获得下一条数据
    public function getNextData($id,$desc=1){
        $cid = $this->where('id='.$id)->getField('cid');
        if($desc){//降序
            $data = $this->where('id>'.$id.' AND cid='.$cid.' and is_show=1 and release_time<'.time())->field('id,title,cid')->order('id ASC')->limit(1)->find();
        }else{
            $data = $this->where('id<'.$id.' AND cid='.$cid.' and is_show=1 and release_time<'.time())->field('id,title,cid')->order('id DESC')->limit(1)->find();
        }
        if(!$data){
            $data = array('title'=>'已经是最后一条了','id'=>$id);
        }
        return $data;
    }
    
    //获取前一条数据
    public function getPreData($id,$desc=1){
        $cid = $this->where('id='.$id)->getField('cid');
        if($desc){//降序
            $data = $this->where('id<'.$id.' AND cid='.$cid.' and is_show=1 and release_time<'.time())->field('id,title,cid')->order('id DESC')->limit(1)->find();
        }else{
            $data = $this->where('id>'.$id.' AND cid='.$cid.' and is_show=1 and release_time<'.time())->field('id,title,cid')->order('id ASC')->limit(1)->find();
        }
        if(!$data){
            $data = array('title'=>'已经是最后一条了','id'=>$id);
        }
        return $data;
    }

    public function lookCount($id){
        $result = $this->where('id='.$id)->setInc('look_count', 1);
        if($result){
            return true;
        }else{
            return false;
        }
    }

    public function getExpand($map){
        $list = M('CategoryExpand')->where('cid='.$map['cid'])->select();
        // $list = M('CategoryExpand')->alias('ce')->field('ce.*,ae.value,ae.id as expand_id')->where('cid='.$map['cid'].' and ae.aid='.$map['aid'])->join('LEFT JOIN __ARTICLE_EXPAND__ as ae on ae.name=ce.c_name')->select();

        if (count($list) != 0) {
            foreach ($list as $key => $value) {
                $data[$key]['c_name'] = $value['c_name'];
                $data[$key]['e_name'] = $value['e_name'];
                $data[$key]['type'] = $value['type'];
                $data[$key]['option'] = explode(',', $value['option']);
                $data[$key]['cid'] = $value['cid'];
                $data[$key]['id'] = $value['id'];
                $expand = M('GoodsExpand')->where('aid='.$map['aid'].' and name="'.$value['c_name'].'"')->find();
                $data[$key]['value'] = $expand['value'];
                $data[$key]['expand_id'] = $expand['id'];
            }
        }
        return $data;
    }

    public function addExpand($data,$aid){
        $count = count($data['name']);
        for($i=0; $i<$count; $i++) {
            $expand['name'] = $data['name'][$i];
            $expand['value'] = $data['value'][$i];
            $expand['aid'] = $aid;
            if($data['expand_id'][$i] != null){
                $expand['id'] = $data['expand_id'][$i];
                M('GoodsExpand')->save($expand);
                unset($expand);
            }else{
                M('GoodsExpand')->add($expand);
            }
        }
    }

    public function getExpandForHome($map){
        $list = M('CategoryExpand')->alias('ce')->field('ce.*,ae.value,ae.id as expand_id')->where('cid='.$map['cid'].' and ae.aid='.$map['aid'])->join('LEFT JOIN __ARTICLE_EXPAND__ as ae on ae.name=ce.c_name')->select();
        foreach ($list as $key => $value) {
            $data[$value['e_name']] = $value['value'];
        }
        return $data;
    }
}
